package com.pet.server.ext.action.task;

import java.util.Date;
import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.TaskInfo;
import com.pet.server.ext.data.UserTask;
import com.pet.server.ext.data.UserTaskDaily;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.DateUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;

public class Integral extends ActionBase{

	private String task_id,task_type;

	public Integral(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		task_id = params.getFieldValue("task_id");
		task_type =params.getFieldValue("task_type");
		if(StringUtil.isEmpty(task_id,task_type)){
			throw ApiError.Type.INVALID_PARAM.toException();	
		}
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		TaskInfo ti = userService.findTaskInfo(task_id, task_type);
		if(null==ti){
			throw ApiError.Type.LOGIC_ERROR.toException("任务不存在!");		
		}
		if("normal".equals(task_type)){
			UserTask ut = userService.findUserTask(user.user_id,task_id);
			if(ut==null||BaseAttribute.LOGIC_TRUE.equals(ut.received)){
				throw ApiError.Type.LOGIC_ERROR.toException("任务不存在!");	
			}
			userService.addScroeByUserTask(user.user_id, task_id, ti);
		}else if("daily".equals(task_type)){
			String date = DateUtil.getFormatDate(new Date(), "yyyy-MM-dd");
			UserTaskDaily utd = userService.findUserTaskDaily(user.user_id, task_id, date);
			if(utd==null||BaseAttribute.LOGIC_TRUE.equals(utd.received)){
				throw ApiError.Type.LOGIC_ERROR.toException("任务不存在!");	
			}
			userService.addScroeByUserTaskDaily(date, user.user_id, task_id, ti);
		}else{
			throw ApiError.Type.LOGIC_ERROR.toException("任务类型不存在!");	
		}
		Result result = new Result();
		result.put("message", "success");
	    return result;
	}
}
